import random
from datetime import datetime

class BankSystem:
    def __init__(self):
        self.users = {}  # 存储用户数据：key=银行卡号，value=用户信息字典
        self.current_user = None  # 当前登录用户（卡号）
        # 管理员账户信息（可根据需求修改）
        self.admin_account = "Nana"
        self.admin_password = "050926"

    def generate_card_number(self):
        """生成8位唯一银行卡号"""
        while True:
            card_num = str(random.randint(10000000, 99999999))
            if card_num not in self.users:
                return card_num

    def is_valid_password(self, password):
        """验证密码格式（6位数字）"""
        return len(password) == 6 and password.isdigit()

    def admin_login(self):
        """管理员登录验证"""
        print("请输入管理员账户：", end="")
        account = input().strip()
        if account != self.admin_account:
            print("管理员账户输入错误......")
            return False
        print("请输入密码：", end="")
        pwd = input().strip()
        if pwd != self.admin_password:
            print("输入密码有误......")
            return False
        print("操作成功，请稍后......")
        return True

    def open_account(self):
        """开户功能"""
        print("\n===== 开户服务 =====")
        name = input("请输入姓名：").strip()
        if not name:
            print("姓名不能为空！")
            return

        id_card = input("请输入身份证号：").strip()
        if len(id_card) != 18:
            print("身份证号必须是18位！")
            return

        password = input("请设置6位数字密码：").strip()
        if not self.is_valid_password(password):
            print("密码格式错误！必须是6位数字")
            return

        confirm_pwd = input("请确认密码：").strip()
        if password != confirm_pwd:
            print("两次密码不一致！开户失败")
            return

        # 生成卡号并创建用户信息
        card_num = self.generate_card_number()
        self.users[card_num] = {
            "name": name,
            "id_card": id_card,
            "password": password,
            "balance": 0.0,
            "is_locked": False,
            "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }

        print(f"\n开户成功！")
        print(f"您的银行卡号：{card_num}")
        print(f"开户时间：{self.users[card_num]['create_time']}")
        print("请妥善保管您的卡号和密码！")

    def login_verify(self):
        """登录验证（用于操作前身份确认）"""
        if self.current_user:
            return True  # 已登录直接返回

        print("\n===== 身份验证 =====")
        card_num = input("请输入银行卡号：").strip()
        if card_num not in self.users:
            print("卡号不存在！")
            return False

        user = self.users[card_num]
        if user["is_locked"]:
            print("该账户已锁定！请联系银行解锁")
            return False

        # 密码验证（最多3次机会）
        for _ in range(3):
            password = input("请输入密码：").strip()
            if password == user["password"]:
                self.current_user = card_num
                print(f"登录成功！欢迎您，{user['name']}先生/女士")
                return True
            else:
                print(f"密码错误！还有{2 - _}次机会")
        else:
            # 3次错误锁定账户
            user["is_locked"] = True
            print("密码连续3次错误，账户已锁定！")
            return False

    def query_balance(self):
        """查询余额"""
        if not self.login_verify():
            return

        user = self.users[self.current_user]
        print(f"\n===== 余额查询 =====")
        print(f"账户姓名：{user['name']}")
        print(f"银行卡号：{self.current_user}")
        print(f"当前余额：{user['balance']:.2f} 元")
        print(f"查询时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    def withdraw_money(self):
        """取款功能"""
        if not self.login_verify():
            return

        user = self.users[self.current_user]
        print(f"\n===== 取款服务 =====")
        print(f"当前余额：{user['balance']:.2f} 元")

        try:
            amount = float(input("请输入取款金额：").strip())
            if amount <= 0:
                print("取款金额必须大于0！")
                return
            if amount > user["balance"]:
                print("余额不足！取款失败")
                return
            # 模拟取款手续费（可根据需求调整或删除）
            service_fee = amount * 0.005  # 0.5%手续费，最低1元
            service_fee = max(service_fee, 1.0)
            if amount + service_fee > user["balance"]:
                print(f"扣除手续费后余额不足！手续费：{service_fee:.2f}元")
                return

            # 执行取款操作
            user["balance"] -= (amount + service_fee)
            print(f"\n取款成功！")
            print(f"取款金额：{amount:.2f} 元")
            print(f"手续费：{service_fee:.2f} 元")
            print(f"剩余余额：{user['balance']:.2f} 元")
        except ValueError:
            print("输入格式错误！请输入数字")

    def deposit_money(self):
        """存款功能"""
        if not self.login_verify():
            return

        user = self.users[self.current_user]
        print(f"\n===== 存款服务 =====")

        try:
            amount = float(input("请输入存款金额：").strip())
            if amount <= 0:
                print("存款金额必须大于0！")
                return

            # 执行存款操作（无手续费）
            user["balance"] += amount
            print(f"\n存款成功！")
            print(f"存款金额：{amount:.2f} 元")
            print(f"当前余额：{user['balance']:.2f} 元")
            print(f"存款时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        except ValueError:
            print("输入格式错误！请输入数字")

    def transfer_money(self):
        """转账功能"""
        if not self.login_verify():
            return

        user = self.users[self.current_user]
        print(f"\n===== 转账服务 =====")
        print(f"当前余额：{user['balance']:.2f} 元")

        target_card = input("请输入对方银行卡号：").strip()
        if target_card not in self.users:
            print("对方卡号不存在！转账失败")
            return
        if target_card == self.current_user:
            print("不能向自己转账！")
            return

        target_user = self.users[target_card]
        print(f"对方账户：{target_user['name']}（卡号：{target_card}）")
        confirm = input("是否确认向该账户转账？（y/n）：").strip().lower()
        if confirm != "y":
            print("转账已取消")
            return

        try:
            amount = float(input("请输入转账金额：").strip())
            if amount <= 0:
                print("转账金额必须大于0！")
                return
            # 模拟转账手续费
            service_fee = amount * 0.003  # 0.3%手续费，最低1元，最高50元
            service_fee = max(min(service_fee, 50.0), 1.0)
            total_amount = amount + service_fee

            if total_amount > user["balance"]:
                print(f"余额不足！转账金额+手续费：{total_amount:.2f}元")
                print(f"手续费：{service_fee:.2f}元")
                return

            # 执行转账操作
            user["balance"] -= total_amount
            target_user["balance"] += amount
            print(f"\n转账成功！")
            print(f"转账金额：{amount:.2f} 元")
            print(f"手续费：{service_fee:.2f} 元")
            print(f"剩余余额：{user['balance']:.2f} 元")
        except ValueError:
            print("输入格式错误！请输入数字")

    def lock_account(self):
        """锁定账户（需本人验证）"""
        if not self.login_verify():
            return

        user = self.users[self.current_user]
        if user["is_locked"]:
            print("\n该账户已处于锁定状态！")
            return

        confirm = input("\n确认要锁定账户吗？锁定后需本人携带身份证解锁（y/n）：").strip().lower()
        if confirm == "y":
            user["is_locked"] = True
            self.current_user = None  # 锁定后强制退出登录
            print("账户锁定成功！")
        else:
            print("锁定操作已取消")

    def unlock_account(self):
        """解锁账户（需身份验证）"""
        print("\n===== 账户解锁 =====")
        card_num = input("请输入被锁定的银行卡号：").strip()
        if card_num not in self.users:
            print("卡号不存在！")
            return

        user = self.users[card_num]
        if not user["is_locked"]:
            print("该账户未锁定，无需解锁！")
            return

        # 身份验证（姓名+身份证号）
        name = input("请输入账户姓名：").strip()
        id_card = input("请输入身份证号：").strip()
        if name != user["name"] or id_card != user["id_card"]:
            print("姓名或身份证号验证失败！解锁失败")
            return

        # 验证通过，解锁账户
        user["is_locked"] = False
        print("账户解锁成功！请重新登录")

    def logout(self):
        """退出登录"""
        if self.current_user:
            print(f"\n再见，{self.users[self.current_user]['name']}先生/女士！")
            self.current_user = None
        else:
            print("\n您尚未登录")

    def show_welcome(self):
        """显示欢迎登录界面"""
        print("\n" + "*"*40)
        print("*"*6 + " "*(40-12) + "*"*6)
        print("*"*6 + " 欢迎登录银行管理系统 " + "*"*6)
        print("*"*6 + " "*(40-12) + "*"*6)
        print("*"*40)

    def show_menu(self):
        """显示功能菜单界面"""
        print("\n" + "*"*40)
        print("*"*6 + " "*(40-12) + "*"*6)
        print("*"*6 + " 1.开户(1)    2.查询(2) " + "*"*6)
        print("*"*6 + " 3.取款(3)    4.存款(4) " + "*"*6)
        print("*"*6 + " 5.转账(5)    6.锁定(6) " + "*"*6)
        print("*"*6 + " 7.解锁(7)        " + "*"*6)
        print("*"*6 + " 退出(Q)          " + "*"*6)
        print("*"*6 + " "*(40-12) + "*"*6)
        print("*"*40)

    def run(self):
        """系统主流程：先管理员登录，再展示欢迎界面和功能菜单"""
        if not self.admin_login():
            print("系统退出！")
            return
        self.show_welcome()
        while True:
            self.show_menu()
            choice = input("请选择功能（1-7 或者 Q）：").strip()
            if choice == "1":
                self.open_account()
            elif choice == "2":
                self.query_balance()
            elif choice == "3":
                self.withdraw_money()
            elif choice == "4":
                self.deposit_money()
            elif choice == "5":
                self.transfer_money()
            elif choice == "6":
                self.lock_account()
            elif choice == "7":
                self.unlock_account()
            elif choice == "Q":
                self.logout()
                print("感谢使用银行管理系统，再见！")
                break
            else:
                print("输入错误！请选择0-7之间的数字")

if __name__ == "__main__":
    bank = BankSystem()
    bank.run()